package org.graduates.webapp.actions.file;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.graduates.webapp.actions.BaseAction;
import org.projects.graduates.Constants;

import com.opensymphony.xwork2.ActionSupport;

@ParentPackage("web")
@Action(results = { @Result(name = "success", type = "json") })
public class FileManagerAction extends BaseAction {

	private static final long serialVersionUID = 5250151696648575437L;

	private String dir;

	private String order;

	@SuppressWarnings("rawtypes")
	List<Hashtable> file_list = new ArrayList<Hashtable>();

	private int total_count;

	private String current_url;

	private String current_dir_path;

	private String moveup_dir_path;

	private String path;

	// kindeditor在线编辑器必需
	private int error = 0;

	// kindeditor在线编辑器必需
	private String message;
	// 图片扩展名
	private String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp" };

	public String execute() {
		
		String separator = File.separator;
		
		long pId = getCurrentPerson().getId();

		String rootPath = ServletActionContext.getServletContext().getRealPath("/") + separator + Constants.UPLOAD_DIR + separator + getCurrentPerson().getId()  +separator;

		String rootUrl = ServletActionContext.getServletContext().getContextPath() + "/" + Constants.UPLOAD_DIR + "/" + pId + "/" ;

		if (!Arrays.<String> asList(new String[] { "image", "flash", "media", "file" }).contains(dir)) {
			setError("无效文件夹");
			return ActionSupport.SUCCESS;
		}

		File saveDirFile = new File(rootPath);
		if (!saveDirFile.exists()) {
			saveDirFile.mkdirs();
		}

		String current_path = rootPath + path;

		current_dir_path = path;

		current_url = rootUrl + path;

		if (!"".equals(path)) {
			String str = current_dir_path.substring(0, current_dir_path.length() - 1);
			moveup_dir_path = str.lastIndexOf("/") >= 0 ? str.substring(0, str.lastIndexOf("/") + 1) : "";
		}

		order = order != null ? order.toLowerCase() : "name";


		// 不允许使用..移动到上一级目录
		if (path.indexOf("..") >= 0) {
			setError("Access is not allowed.");
			return ActionSupport.SUCCESS;
		}

		// 最后一个字符不是/
		if (!"".equals(path) && !path.endsWith("/")) {
			setError("Parameter is not valid.");
			return ActionSupport.SUCCESS;
		}

		// 目录不存在或不是目录
		File currentPathFile = new File(current_path);
		if (!currentPathFile.isDirectory()) {
			setError("Directory does not exist.");
			return ActionSupport.SUCCESS;
		}

		if (currentPathFile.listFiles() != null) {
			for (File file : currentPathFile.listFiles()) {
				Hashtable<String, Object> hash = new Hashtable<String, Object>();
				String fileName = file.getName();
				if (file.isDirectory()) {
					hash.put("is_dir", true);
					hash.put("has_file", (file.listFiles() != null));
					hash.put("filesize", 0L);
					hash.put("is_photo", false);
					hash.put("filetype", "");
				} else if (file.isFile()) {
					String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
					hash.put("is_dir", false);
					hash.put("has_file", false);
					hash.put("filesize", file.length());
					hash.put("is_photo", Arrays.<String> asList(fileTypes).contains(fileExt));
					hash.put("filetype", fileExt);
				}
				hash.put("filename", fileName);
				hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));
				file_list.add(hash);
			}
		}

		if ("size".equals(order)) {
			Collections.sort(file_list, new SizeComparator());
		} else if ("type".equals(order)) {
			Collections.sort(file_list, new TypeComparator());
		} else {
			Collections.sort(file_list, new NameComparator());
		}
		total_count = file_list.size();
		return ActionSupport.SUCCESS;
	}

	private void setError(String message) {
		this.error = 1;
		this.message = message;
	}

	public String getDir() {
		return dir;
	}

	public void setDir(String dir) {
		this.dir = dir;
	}

	public String getOrder() {
		return order;
	}

	public void setOrder(String order) {
		this.order = order;
	}

	@SuppressWarnings("rawtypes")
	public List<Hashtable> getFile_list() {
		return file_list;
	}

	@SuppressWarnings("rawtypes")
	public void setFile_list(List<Hashtable> file_list) {
		this.file_list = file_list;
	}

	public int getTotal_count() {
		return total_count;
	}

	public void setTotal_count(int total_count) {
		this.total_count = total_count;
	}

	public String getCurrent_url() {
		return current_url;
	}

	public void setCurrent_url(String current_url) {
		this.current_url = current_url;
	}

	public String getCurrent_dir_path() {
		return current_dir_path;
	}

	public void setCurrent_dir_path(String current_dir_path) {
		this.current_dir_path = current_dir_path;
	}

	public String getMoveup_dir_path() {
		return moveup_dir_path;
	}

	public void setMoveup_dir_path(String moveup_dir_path) {
		this.moveup_dir_path = moveup_dir_path;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public int getError() {
		return error;
	}

	public void setError(int error) {
		this.error = error;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

}
